package com.lanelu.hencoderplusstudy.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.lanelu.hencoderplusstudy.R


private val IMG_SIZE = 150.dp
private val IMG_PADDING = 50.dp

//换行
class MultilineTextView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    val text =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
                "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
                "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
                "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. " +
                "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 20.dp
    }
    private val bitmap = getAvatar(IMG_SIZE.toInt(), R.drawable.avatar_rengwuxian)
    private val fontMetrics = Paint.FontMetrics()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(bitmap, width - IMG_SIZE, IMG_PADDING, paint)
        paint.getFontMetrics(fontMetrics)
        val measuredWidth = floatArrayOf(0f)

        var start = 0 //起始位置
        var count: Int //每行显示的文字数
        var verticalOffset = -fontMetrics.top//纵向偏移
        var maxWidth: Float//显示最大宽度

        while (start < text.length) {
            if (verticalOffset + fontMetrics.bottom < IMG_PADDING || verticalOffset + fontMetrics.top > IMG_PADDING + IMG_SIZE) {
                //图片范围之外
                maxWidth = width.toFloat()
            } else {
                //图片范围之内
                maxWidth = width.toFloat() - IMG_SIZE
            }
            count = paint.breakText(text, start, text.length, true, maxWidth, measuredWidth)
            canvas.drawText(text, start, start + count, 0f, verticalOffset, paint)
            start += count
            verticalOffset += paint.fontSpacing
        }

    }


    fun getAvatar(width: Int, resourceId: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true//第一次只是获取图片尺寸
        BitmapFactory.decodeResource(resources, resourceId, options)//先读取一次图片尺寸
        options.inJustDecodeBounds = false//第二次需要完整的读取图片
        options.inDensity = options.outWidth//图片原先尺寸
        options.inTargetDensity = width//图片目标尺寸
        return BitmapFactory.decodeResource(resources, resourceId, options)
    }


}